﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NETCore.Auth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;
using Auth.Classic.Filters;
namespace Auth.Classic.Controllers
{
    [MyTempFilter]
    public class AccountController : Controller
    {

        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(IFormCollection formData)
        {
            string userName = formData["username"].ToString();
            string password = formData["password"].ToString();
            string loginType = formData["loginType"].ToString();
            if (userName == "test" && password == "123456")
            {
                // 登录成功，创建CurrentUser类
                CurrentUser currentUser = new CurrentUser { Id = 123, Name = "张三", Account = userName };

                string userJson = JsonSerializer.Serialize(currentUser);

                if (loginType == "cookie")
                {
                    // 记录cookie，通过Response传到浏览器
                    HttpContext.Response.Cookies.Append("CurrentUser", userJson, new CookieOptions
                    {
                        Expires = DateTime.Now.AddMinutes(30)
                    });
                }
                else //session
                {
                    HttpContext.Session.SetString("CurrentUser", userJson);
                }

                // 设置一个cookie保存当前用户信息保存的位置 cookie/session
                HttpContext.Response.Cookies.Append("LoginType", loginType);
            }
            else
            {
                TempData["err"] = "账号或密码不正确";
                //账号密码不对,跳回登录页
                return RedirectToAction(nameof(Login), "Account");
            }

            return RedirectToAction("Index", "Home");
        }


        public IActionResult LogOut()
        {
            HttpContext.Response.Cookies.Delete("CurrentUser");
            return RedirectToAction(nameof(Login), "Account");

        }
    }
}
